<!-- 充值回调查询 -->
<template>
  <div>
    <el-card>
      <div class="topInquire">
        <div>
          <!-- 渠道 -->
          <Channel @channel-event="handleSelectChannel"></Channel>
        </div>
  
        <div>
          <!-- 服务器 -->
          <Server @server-event="handleSelectServer"></Server>
        </div>

        <div>
          <span>发货状态 </span>
          <el-select v-model.number="orderStatus" size="small" style="width:200px" clearable>
            <el-option :value="0" label="全部" />
            <el-option :value="1" label="发货成功" />
            <el-option :value="2" label="发货失败" />
          </el-select>
        </div>

        <div>
          <span>订单号查询 </span>
          <el-input v-model.number="orderNumber" size="small" style="width:200px" clearable placeholder="请输入订单号" />
        </div>

        <div>
          <span>玩家ID </span>
          <el-input v-model.trim="playerId" style="width:200px" size="small" clearable placeholder="请输入" />
        </div>

        <div>
          <!-- 日期 -->
          <DatePicker @dateChange="handleDateChange"></DatePicker>
          </div>

        <el-button size="small" icon="el-icon-search" type="primary" @click="handleSearch">搜索</el-button>
      
        <el-button icon="el-icon-upload2" type="success" 
            size="small" @click="handleExport">导出Excel</el-button>
      </div>

      <div>
        <el-table
          ref="table"
          border
          :data="rechargeData"
          :height="tableHeight"
          :header-cell-style="{background:'#f5f7fa'}"
        >
          <el-table-column prop="id" label="数据ID" width="120" />
          <el-table-column prop="channelInfo" label="渠道信息" min-width="150" />
          <el-table-column prop="serverInfo" label="服务器信息" min-width="150" />
          <el-table-column prop="sdkOrderId" label="渠道订单号" width="250" />
          <el-table-column prop="gameOrderId" label="游戏服订单号" width="250" />
          <el-table-column prop="playerId" label="玩家ID" min-width="150" />
          <el-table-column prop="nick" label="角色名" min-width="150" />
          <el-table-column prop="payMoney" label="充值金额（单位：元）" min-width="180" />
          <el-table-column prop="rechargeTime" label="充值时间" min-width="180">
            <template #default="{row}">{{ row.rechargeTime|formatTime }}</template>
          </el-table-column>
          <el-table-column prop="productName" label="充值商品" min-width="150" />
          <el-table-column prop="productType" label="商品类型" min-width="150" />
          <el-table-column prop="rewards" label="奖品" min-width="500" />
          <el-table-column prop="prePayMoney" label="预付金额（单位：元）" min-width="180"/>
          <el-table-column prop="level" label="角色等级" min-width="150" />
          <el-table-column prop="vipLevel" label="VIP等级" min-width="150" />
          <el-table-column prop="status" label="订单状态" min-width="150">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 1 ?'success' : 'danger'">
                {{ scope.row.status === 1 ?'发货成功' : '发货失败' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="statusText" label="订单详情" min-width="150" />
          <el-table-column prop="memo" label="备注" min-width="300" />
          <el-table-column fixed="right" label="操作" width="120">
            <template slot-scope="scope">
              <el-button
                v-show="scope.row.status!==1"
                size="small"
                type="primary"
                plain
                icon="el-icon-edit"
                @click="handleReplenishment(scope.row.id)"
              >人工补单</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <el-pagination
        background
        layout="total, prev, pager, next, jumper"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        @current-change="changePage"
      />
    </el-card>
  </div>

</template>

<script>
  import Channel from '@/components/selectChannel/index.vue'
  import Server from '@/components/selectServer/index.vue'
  import DatePicker from '@/components/datePicker/index.vue'
  import { export_json_to_excel } from '@/widget/Export2Excel'
  import {recharge,manualRecharge} from '@/api/relatedRecharge'

export default {
  components: {
     Channel,Server,DatePicker
    },
  data() {
    return {
      total: 0,
      rechargeData: [],
      currentPage: 1, // 当前页
      pageSize: 200, // 每页显示条数
      tableHeight: 0, // 表格高度
      orderNumber: '',
      orderStatus: 0,
      playerId:'',
      selectChannel:[],
      selectServer:[],
      date:[]
    }
  },

  created() {
    this.getRecharge()
  },

  mounted() {
    this.$nextTick(() => {
      this.getTableHeight()
    })
    window.addEventListener('resize', this.$debounce(this.getTableHeight, 100))
  },

  beforeDestroy() {
    window.removeEventListener('resize', this.getTableHeight)
  },

  activated() {
    if (this.$refs.table && this.$refs.table.doLayout) {
      this.$refs.table.doLayout()
    }
  },

  methods: {
    // 获取数据
    async getRecharge() {
      const res = await recharge({
        page: this.currentPage,
        limit: this.pageSize
      })
      this.total = res.data.data.count
      this.rechargeData = res.data.data.data
    },

    // 选择日期
    handleDateChange(dateRange){
      this.date = dateRange
    },

    // 选中的渠道
    handleSelectChannel(value){
      this.selectChannel = value
    },

    // 选中的服务器
    handleSelectServer(value){
      this.selectServer = value
    },

    // 搜索
    async handleSearch() {
      try {
        const query = {
          page: this.currentPage,
          limit: this.pageSize
        }

        if (this.date && this.date.length === 2) {
          // 时间戳毫秒转化为秒
          query.startTime = this.$moment(this.date[0]).unix()
          query.endTime = this.$moment(this.date[1]).unix()
        }
        if (this.selectChannel.length !== 0) {
          query.channels = this.selectChannel
        }
        if (this.selectServer.length !== 0) {
          query.serverUids = this.selectServer
        }
        if (this.orderStatus) {
          query.status = this.orderStatus
        }
        if (this.orderNumber) {
          query.sdkOrderId = this.orderNumber
        }
        if (this.playerId) {
          query.playerId = this.playerId
        }

        const result = await recharge(query)
        this.rechargeData = result.data.data.data
        this.total = result.data.data.count
      } catch (error) {
        console.error(error)
        this.$message.error('发生错误，请稍后重试')
      }
    },

    // 人工补单
    async handleReplenishment(id) {
      const res = await manualRecharge({ rechargeId: id })
      if (res.data.code === 0) {
        this.$message.success('补单成功！')
      } else {
        this.$message.error('补单失败！')
      }
    },

    // 切换页面
    changePage(page) {
      this.currentPage = page
      this.getRecharge()
    },

    // 表格自适应高度
    getTableHeight() {
      if (this.$refs.table && this.$refs.table.$el) {
        this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 170
      } else {
        this.tableHeight = 300
      }
    },

    // 导出
     async handleExport() {
       try {
          const res = await recharge({
            limit: this.total
          })
  
          // 处理导出数据
          const exportData = res.data.data.data.map(i => {
            // 充值时间
            const rechargeTime = this.$options.filters.formatTime(i.rechargeTime)
            // 订单状态
            const status = i.status ? '发货成功' : '发货失败'
  
            return { ...i,rechargeTime,status }
          })
  
          const newData = exportData.map(item => {
            const arr = []
            const obj = {
              id: '数据ID',
              channelInfo: '渠道信息',
              serverInfo:'服务器信息',
              sdkOrderId: '渠道订单号',
              gameOrderId: '游戏服订单号',
              playerId: '玩家ID',
              nick: '角色名',
              payMoney: '充值金额',
              rechargeTime: '充值时间',
              productName: '充值商品',
              productType: '商品类型',
              rewards: '奖品',
              prePayMoney: '预付金额',
              level: '角色等级',
              vipLevel: 'VIP等级',
              status: '订单状态',
              statusText: '订单详情',
              memo: '备注',
            }
            for (const key in obj) {
              arr.push(item[key])
            }
            return arr
          })
  
          const tHeader = [
            '数据ID', '渠道信息', '服务器信息', '渠道订单号','游戏服订单号', '玩家ID', 
            '角色名', '充值金额（单位：元）','充值时间','充值商品','商品类型','奖品','预付金额（单位：元）',
            '角色等级','VIP等级','订单状态','订单详情','备注' ]
  
          export_json_to_excel({
            header: tHeader,
            data: newData,
            filename: `充值回调查询表${this.$moment(new Date()).format('YYYYMMDDHHmm')}`,
            autoWidth: true,
            bookType: 'xlsx'
          })
        } catch (error) {
          this.$message.error(error)
        }
      },
  }
}
</script>
<style lang="scss" scoped>

.topInquire{
  font-weight: bold;
  font-size: 14px;
  color: #6a7488;
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
}

</style>
